package com.dataeco.api.service.impl;

import com.dataeco.api.entity.User;
import com.dataeco.api.repository.UserRepository;
import com.dataeco.api.security.JwtTokenService;
import com.dataeco.api.security.SecurityUserDetails;
import com.dataeco.api.security.SecurityUserDetailsService;
import com.dataeco.api.service.AuthService;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl implements AuthService {
    private final UserRepository userRepository;
    private final AuthenticationManager authenticationManager;
    private final SecurityUserDetailsService securityUserDetailsService;
    private final JwtTokenService jwtTokenService;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    public AuthServiceImpl(UserRepository userRepository, AuthenticationManager authenticationManager, SecurityUserDetailsService securityUserDetailsService, JwtTokenService jwtTokenService) {
        this.authenticationManager = authenticationManager;
        this.securityUserDetailsService = securityUserDetailsService;
        this.jwtTokenService = jwtTokenService;
        this.userRepository = userRepository;

    }
    @Override
    public String accessToken(String username, String password) {
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        final Authentication authentication = authenticationManager.authenticate(upToken);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        final UserDetails userDetails = securityUserDetailsService.loadUserByUsername(username);
        return jwtTokenService.generateToken((SecurityUserDetails) userDetails);
    }

    @Override
    public String refreshToken(String refreshToken) {
        final String token = refreshToken.substring(tokenHead.length());
        String username = jwtTokenService.getUsernameFromToken(token);
//        SecurityUserDetailsService user = (SecurityUserDetailsService) userDetailsService.loadUserByUsername(username);
        return jwtTokenService.refreshToken(token);
    }



    @Override
    public boolean authenticate(String loginName, String loginPass) {
        User user = userRepository.findByEmail(loginName);
        if (user == null) {
            throw new UnknownAccountException();
        }
        return false;
    }
}
